using Microsoft.Win32;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace FileManager.Services
{
    public class DatabaseBackupService
    {
        private readonly string _dbPath;
        private readonly string _backupDirectory;

        public DatabaseBackupService()
        {
            _dbPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "WeChatFileManager",
                "wechat_file_manager.db");

            _backupDirectory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "WeChatFileManager",
                "Backups");

            // 确保备份目录存在
            Directory.CreateDirectory(_backupDirectory);
        }

        public async Task<string> CreateBackupAsync()
        {
            try
            {
                if (!File.Exists(_dbPath))
                {
                    MessageBox.Show("数据库文件不存在，无法创建备份", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return null;
                }

                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                string backupPath = Path.Combine(_backupDirectory, $"backup_{timestamp}.db");

                // 复制数据库文件
                await Task.Run(() => File.Copy(_dbPath, backupPath, true));

                MessageBox.Show($"数据库备份成功\n备份路径: {backupPath}", "备份成功", MessageBoxButton.OK, MessageBoxImage.Information);
                return backupPath;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建备份时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }
        }

        public async Task<bool> RestoreBackupAsync(string backupPath = null)
        {
            try
            {
                // 如果未指定备份路径，则弹出文件选择对话框
                if (string.IsNullOrEmpty(backupPath))
                {
                    var openFileDialog = new OpenFileDialog
                    {
                        Filter = "数据库文件 (*.db)|*.db",
                        InitialDirectory = _backupDirectory,
                        Title = "选择要恢复的备份文件"
                    };

                    if (openFileDialog.ShowDialog() != true)
                        return false;

                    backupPath = openFileDialog.FileName;
                }

                if (!File.Exists(backupPath))
                {
                    MessageBox.Show("备份文件不存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // 确保数据库目录存在
                Directory.CreateDirectory(Path.GetDirectoryName(_dbPath));

                // 恢复前先创建当前数据库的临时备份
                string tempBackupPath = Path.Combine(_backupDirectory, $"temp_backup_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.db");
                if (File.Exists(_dbPath))
                {
                    await Task.Run(() => File.Copy(_dbPath, tempBackupPath, true));
                }

                // 恢复数据库
                await Task.Run(() => File.Copy(backupPath, _dbPath, true));

                MessageBox.Show("数据库恢复成功", "恢复成功", MessageBoxButton.OK, MessageBoxImage.Information);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"恢复备份时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }

        public string[] GetAvailableBackups()
        {
            try
            {
                return Directory.GetFiles(_backupDirectory, "backup_*.db");
            }
            catch (Exception)
            {
                return new string[0];
            }
        }

        public async Task<bool> DeleteBackupAsync(string backupPath)
        {
            try
            {
                if (File.Exists(backupPath))
                {
                    await Task.Run(() => File.Delete(backupPath));
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}